package com.cade.agriculturemall.widget;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.cade.agriculturemall.R;


/**
 * Created by Lobby on 2017/8/11.
 * 自定义  Edittext  自带删除按钮
 *
 *
 */

public class CleanEditText extends AppCompatEditText {
    private String TAG = CleanEditText.class.getSimpleName();
    private Drawable dRight;
    private Rect rBounds;
    private Context context;
    private int offset;
    private boolean isEmpty = true;//输入是否为空，默认为true

    public CleanEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        bindListener();

    }

    public CleanEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        bindListener();


        /**
         *设置该空间的drawleft内件与文字的距离，即内边距
         */
        int padding = (int) (context.getResources().getDisplayMetrics().density * 4);
        setCompoundDrawablePadding(padding);

    }

    public CleanEditText(Context context) {
        super(context);
        this.context = context;
        bindListener();
    }

    private void bindListener() {
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                Log.i(TAG, "-----afterTextChanged-----");
                isEmpty = TextUtils.isEmpty(s) ? true : false;
                //输入框内容不为空，并且有焦点
                if (!isEmpty && hasFocus()) {

                    //这可以根据自己的需求替换成自己喜欢的删除图片
                    Drawable drawable = context.getResources().getDrawable(R.mipmap.et_clean);

                    //这行代码是必须的  否则图片会不显示
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    setClearDrawable(drawable);
                } else {
                    setClearDrawable(null);
                }

            }
        });
        setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
//                Log.i(TAG, "-----onFocusChange-----");
//                Log.i(TAG, "hasFocus:" + hasFocus());
                //输入框内容不为空，并且有焦点
                if (!isEmpty && hasFocus) {
                    Drawable drawable = context.getResources().getDrawable(R.drawable.am_et_clean);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    setClearDrawable(drawable);
                } else {
                    setClearDrawable(null);
                }
                if (onCleanFocusChangeListener != null){
                    onCleanFocusChangeListener.onFocusChange(v, hasFocus);
                }
            }

        });}

        /**
         * 这个方法是配合padding来用的，是根据我自己的实际需求添加的， 大家可以不用关心offset有什么用
         *
         * @param right
         * @param offset
         */
    public void setClearDrawable(Drawable right, int offset) {
        this.offset = offset;
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
    }

    private OnFocusChangeListener onCleanFocusChangeListener;

    public void setOnCleanFocusChangeListener(OnFocusChangeListener onCleanFocusChangeListener) {
        this.onCleanFocusChangeListener = onCleanFocusChangeListener;
    }

    /**
     * @param right
     */
    public void setClearDrawable(Drawable right) {
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]);

    }

    @Override
    public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
        if (right != null) {
            dRight = right;
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP && dRight != null) {
            rBounds = dRight.getBounds();
            final int x = (int) event.getX();
            final int y = (int) event.getY();
            //判断点击区域是否在删除按钮的区域内
            if (x >= (this.getRight() - offset - rBounds.width() - dp2px(context, 15) * 2)
                    && x <= (this.getRight() - this.getPaddingRight())
                    && y >= this.getPaddingTop()
                    && y <= (this.getHeight() - this.getPaddingBottom())
                    && getCompoundDrawables()[2] != null
                    ) {
                this.setText("");
                //阻止键盘弹出
                event.setAction(MotionEvent.ACTION_CANCEL);
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        dRight = null;
        rBounds = null;
        super.finalize();
    }

    /**
     * dp转px
     *
     * @param context
     * @return
     */
    public int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

}

